package com.smproject.controller;

import com.smproject.config.redis.RedisUtil;
import com.smproject.entity.SysUserInfo;
import com.smproject.exception.ModelVailException;
import com.smproject.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author hu.liang
 * @Date 2019/7/2 0002
 */
@Controller
@RequestMapping(value = "/api/user")
public class LoginController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 进入登录页面
     * @return
     */
    @RequestMapping(value = "/findLoginPage",method = RequestMethod.GET)
    public ModelAndView findLoginPage(){
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request,String loginName,String password){
        SysUserInfo userInfo = this.sysUserService.findByLoginName(loginName);
        if(Objects.nonNull(userInfo)){
            HttpSession session = request.getSession();
            session.setAttribute("loginUserId",userInfo.getUserId());
            //用户保存至redis
            redisUtil.set("user_id_"+userInfo.getUserId(),session.getId());
            Map<String,Object> result = new HashMap<>();
            result.put("status",true);
            result.put("msg","登录成功!");
            return result;
        }else{
            throw new ModelVailException("用户不存在!");
        }
    }

    @RequestMapping(value = "/findUserId",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> findUserId(Integer userId){
        Map<String,Object> result = new HashMap<>();
        SysUserInfo userInfo = this.sysUserService.findOne(userId);
        if(Objects.nonNull(userInfo)){
            result.put("status",true);
            result.put("data",userInfo);
            return result;
        }else{
            throw new ModelVailException("用户不存在!");
        }
    }


}
